﻿using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Net.Security;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SelfService.Model.Models;
using TT;
using WalkingTec.Mvvm.Core;

namespace SelfService.Services
{
    public class MessageSendService
    {
        private readonly WTMContext _context;

        public MessageSendService(WTMContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<Result<string>> SendAsync(string mobile, string content)
        {
            var secretName = _context.ConfigInfo.AppSettings["SecretName"];
            var secretKey = _context.ConfigInfo.AppSettings["SecretKey"];
            var host = _context.ConfigInfo.AppSettings["Host"];
            if (string.IsNullOrWhiteSpace(secretName)) return new Result<string>("secretName不能为空");
            if (string.IsNullOrWhiteSpace(secretKey)) return new Result<string>("secretKey不能为空"); 
            if (string.IsNullOrWhiteSpace(host)) return new Result<string>("host不能为空"); 
            var pattern = @"^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7\d|8\d|9[189])\d{8}$";
            if (!Regex.IsMatch(mobile, pattern)) return new Result<string>("请检查手机号码是否正确");
            var postData = new
            {
                secretName,
                secretKey,
                mobile,
                content
            };
            var handler = new SocketsHttpHandler
            {
                SslOptions = new SslClientAuthenticationOptions()
                {
                    RemoteCertificateValidationCallback = (sender, certificate, chain, errors) => true
                }
            };
            var helper = new HttpClient(handler);
            var response = await helper.PostAsJsonAsync($"{host}/Sms/Api/Send", postData);
            if (!response.IsSuccessStatusCode) throw new Exception($"通讯失败:{response.StatusCode}");
            var json = await response.Content.ReadAsStringAsync();
            if (!json.TryJsonParse(out SmsSendResponse result, out var error))
            {
                return new Result<string>($"格式化返回数据出错: {error}");
            }

            if (result.code == 0)
            {
                return new Result<string>
                {
                    Code = 200,
                    Message = "success",
                    Data = result.msg
                };
            }

            return new Result<string>($"短信发送失败: {result.msg}");
        }

        /// <summary>
        /// 发送短信并记录到数据库
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public async Task<Result<string>> SendAndLog(string mobile, string content)
        {
            var result = await this.SendAsync(mobile, content);
            var pushLog = new SysSmsPushLog
            {
                ID = Guid.NewGuid(),
                Phone = mobile,
                CreateTime = DateTime.Now,
                PushTime = DateTime.Now,
                State = result.Code == 200 ? PushStateEnum.成功 : PushStateEnum.失败,
                Message = result.Message,
                Context = content,
                CreateById = Guid.Parse(_context.LoginUserInfo.UserId)
            };
            await _context.DC.Set<SysSmsPushLog>().AddAsync(pushLog);
            await _context.DC.SaveChangesAsync();
            return result;
        }
    }
    
    public class SmsSendResponse
    {
        [JsonRequired]
        public int code { get; set; }

        public string msg { get; set; }

        public string data { get; set; }
    }
}
